import { Link, useHistory } from 'react-router-dom'

import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Space,
  Table,
  Tag,
  Modal,
  Input,
} from 'antd'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'

import img404 from '@/assets/error.png'

import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticles, delArticle } from '@/store/actions'

import { Channel } from '@/components/Channel'

const { RangePicker } = DatePicker

const { confirm } = Modal

const Article = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const { page, pageSize, list, count } = useSelector((state) => state.article)

  // 修改数据
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [updateForm] = Form.useForm()

  useEffect(() => {
    dispatch(getArticles())
  }, [dispatch])

  const articleStatus = {
    0: { color: 'yellow', text: '草稿' },
    1: { color: '#ccc', text: '待审核' },
    2: { color: 'green', text: '审核通过' },
    3: { color: 'red', text: '审核失败' },
  }

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover ?? img404} width={200} height={150} alt="" />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        const statusData = articleStatus[data]
        return <Tag color={statusData.color}>{statusData.text}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              // onClick={() => history.push(`/home/publish/${data.id}`)}
              onClick={() => onUpdate(data.id)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => onDelArticle(data.id)}
            />
          </Space>
        )
      },
    },
  ]

  // 删除文章
  const onDelArticle = (id) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除该文章，是否继续？',

      onOk() {
        dispatch(delArticle(id, paramsRef.current))
      },
    })
  }

  // 修改文章
  const onUpdate = (id, paramsRef) => {
    setIsModalVisible(true)
    updateForm.setFieldsValue({
      id,
      a: '666',
      b: 'xxx',
      c: 'sss',
    })
  }

  // 定义筛选参数
  const paramsRef = useRef({})

  // 筛选
  const onSearch = (value) => {
    const { status, channel_id, date } = value
    const params = {}
    if (status !== -1) {
      params.status = status
    }
    if (channel_id !== undefined) {
      params.channel_id = channel_id
    }
    if (date) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD')
      params.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    paramsRef.current = params
    dispatch(getArticles(params))
  }

  // 分页
  const changePage = (page, pageSize) => {
    const params = {
      ...paramsRef.current,
      page,
      per_page: pageSize,
    }
    paramsRef.current = params
    dispatch(getArticles(params))
  }

  // 确认修改或新增
  const handleOk = (value) => {
    console.log(value)
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: -1 }} onFinish={onSearch}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel width={200} />
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        title="修改"
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={[]}
      >
        <Form
          name="basic"
          form={updateForm}
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={handleOk}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            // label="a"
            name="id"
            // rules={[
            //   {
            //     required: true,
            //     message: 'Please input your username!',
            //   },
            // ]}
          >
            <Input type="hidden" />
          </Form.Item>

          <Form.Item
            label="a"
            name="a"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="b"
            name="b"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="c"
            name="c"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={list}
          pagination={{
            current: page,
            pageSize,
            total: count,
            showSizeChanger: true,
            position: ['bottomCenter'],
            onChange: changePage,
          }}
        />
      </Card>
    </div>
  )
}

export default Article
